package com.xinggq.user.service.context;

import com.xinggq.common.constant.AuthConstants;
import com.xinggq.common.context.UserContextProvider;
import com.xinggq.common.context.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * HTTP请求头用户上下文提供者
 * 从HTTP请求头中读取用户信息，用于微服务间的用户信息传递
 * 
 * @author xinggq
 * @since 2025/1/20
 */
@Slf4j
@Component
public class HttpHeaderUserContextProvider implements UserContextProvider {

    @Override
    public UserInfo getCurrentUser() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return null;
        }

        try {
            // 从请求头中获取用户信息
            String userIdStr = request.getHeader(AuthConstants.USER_ID_HEADER);
            String username = request.getHeader(AuthConstants.USER_NAME_HEADER);
            String tenantIdStr = request.getHeader(AuthConstants.TENANT_ID_HEADER);

            // 用户ID是必须的
            if (!StringUtils.hasText(userIdStr)) {
                return null;
            }

            Long userId = Long.parseLong(userIdStr);
            Long tenantId = StringUtils.hasText(tenantIdStr) ? Long.parseLong(tenantIdStr) : null;

            // 创建用户信息对象
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setUsername(username);
            userInfo.setTenantId(tenantId);

            log.debug("从请求头获取用户信息: userId={}, username={}, tenantId={}", 
                     userId, username, tenantId);

            return userInfo;
        } catch (NumberFormatException e) {
            log.warn("解析请求头中的用户信息失败", e);
            return null;
        }
    }

    @Override
    public boolean hasCurrentUser() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return false;
        }

        String userIdStr = request.getHeader(AuthConstants.USER_ID_HEADER);
        return StringUtils.hasText(userIdStr);
    }

    @Override
    public int getPriority() {
        // 高优先级，优先于测试环境提供者
        return 1;
    }

    @Override
    public boolean isApplicable() {
        // 在有HTTP请求上下文时适用
        return getCurrentRequest() != null;
    }

    /**
     * 获取当前HTTP请求
     * 
     * @return HTTP请求对象，如果不在请求上下文中返回null
     */
    private HttpServletRequest getCurrentRequest() {
        try {
            ServletRequestAttributes attributes = 
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attributes != null ? attributes.getRequest() : null;
        } catch (Exception e) {
            log.debug("获取当前HTTP请求失败", e);
            return null;
        }
    }
}